var __defProp = Object.defineProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateWrapper = (obj, member, setter, getter) => ({
  set _(value) {
    __privateSet(obj, member, value, setter);
  },
  get _() {
    return __privateGet(obj, member, getter);
  }
});
var _head, _tail, _size;
import { ipcMain, app, BrowserWindow, Menu } from "electron";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { exec, execFile } from "node:child_process";
class Node {
  constructor(value) {
    __publicField(this, "value");
    __publicField(this, "next");
    this.value = value;
  }
}
class Queue {
  constructor() {
    __privateAdd(this, _head);
    __privateAdd(this, _tail);
    __privateAdd(this, _size);
    this.clear();
  }
  enqueue(value) {
    const node = new Node(value);
    if (__privateGet(this, _head)) {
      __privateGet(this, _tail).next = node;
      __privateSet(this, _tail, node);
    } else {
      __privateSet(this, _head, node);
      __privateSet(this, _tail, node);
    }
    __privateWrapper(this, _size)._++;
  }
  dequeue() {
    const current = __privateGet(this, _head);
    if (!current) {
      return;
    }
    __privateSet(this, _head, __privateGet(this, _head).next);
    __privateWrapper(this, _size)._--;
    return current.value;
  }
  peek() {
    if (!__privateGet(this, _head)) {
      return;
    }
    return __privateGet(this, _head).value;
  }
  clear() {
    __privateSet(this, _head, void 0);
    __privateSet(this, _tail, void 0);
    __privateSet(this, _size, 0);
  }
  get size() {
    return __privateGet(this, _size);
  }
  *[Symbol.iterator]() {
    let current = __privateGet(this, _head);
    while (current) {
      yield current.value;
      current = current.next;
    }
  }
  *drain() {
    while (__privateGet(this, _head)) {
      yield this.dequeue();
    }
  }
}
_head = new WeakMap();
_tail = new WeakMap();
_size = new WeakMap();
function pLimit(concurrency) {
  validateConcurrency(concurrency);
  const queue = new Queue();
  let activeCount = 0;
  const resumeNext = () => {
    if (activeCount < concurrency && queue.size > 0) {
      queue.dequeue()();
      activeCount++;
    }
  };
  const next = () => {
    activeCount--;
    resumeNext();
  };
  const run = async (function_, resolve, arguments_) => {
    const result = (async () => function_(...arguments_))();
    resolve(result);
    try {
      await result;
    } catch {
    }
    next();
  };
  const enqueue = (function_, resolve, arguments_) => {
    new Promise((internalResolve) => {
      queue.enqueue(internalResolve);
    }).then(
      run.bind(void 0, function_, resolve, arguments_)
    );
    (async () => {
      await Promise.resolve();
      if (activeCount < concurrency) {
        resumeNext();
      }
    })();
  };
  const generator = (function_, ...arguments_) => new Promise((resolve) => {
    enqueue(function_, resolve, arguments_);
  });
  Object.defineProperties(generator, {
    activeCount: {
      get: () => activeCount
    },
    pendingCount: {
      get: () => queue.size
    },
    clearQueue: {
      value() {
        queue.clear();
      }
    },
    concurrency: {
      get: () => concurrency,
      set(newConcurrency) {
        validateConcurrency(newConcurrency);
        concurrency = newConcurrency;
        queueMicrotask(() => {
          while (activeCount < concurrency && queue.size > 0) {
            resumeNext();
          }
        });
      }
    }
  });
  return generator;
}
function validateConcurrency(concurrency) {
  if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
    throw new TypeError("Expected `concurrency` to be a number from 1 and up");
  }
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
process.env.APP_ROOT = path.join(__dirname, "..");
const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");
process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, "public") : RENDERER_DIST;
let win;
function createWindow() {
  win = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, "icon.ico"),
    width: 800,
    height: 600,
    fullscreen: true,
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs")
    }
  });
  win.webContents.on("did-finish-load", () => {
    win == null ? void 0 : win.webContents.send("main-process-message", (/* @__PURE__ */ new Date()).toLocaleString());
  });
  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL);
  } else {
    win.loadFile(path.join(RENDERER_DIST, "index.html"));
  }
  Menu.setApplicationMenu(null);
}
ipcMain.handle("win-close", () => {
  if (win) {
    win.close();
  }
});
ipcMain.handle("get-installed-apps", async () => {
  try {
    const apps = await getInstalledAppsOther();
    return { success: true, data: apps };
  } catch (error) {
    return { success: false, error: error.message || error.toString() };
  }
});
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    win = null;
  }
});
ipcMain.handle("open-installed-app", async (event, appPath) => {
  let appPathStr;
  console.log(event);
  console.log(appPath, "appPath");
  try {
    appPathStr = typeof appPath === "string" ? JSON.parse(appPath) : appPath;
  } catch (e) {
    return { success: false, error: "Invalid JSON" };
  }
  if (!appPathStr || !appPathStr.DisplayIcon || !appPathStr.DisplayIcon.includes(".exe")) {
    return { success: false, error: "Invalid path" };
  }
  const rawPath = onAppDoubleClick(appPathStr);
  const needsQuotes = !/^".+"$/.test(rawPath);
  const safePath = needsQuotes ? `"${rawPath.replace(/"/g, '\\"')}"` : rawPath;
  const command = `powershell -NoProfile -Command Start-Process -FilePath '${safePath}' -Verb RunAs`;
  return new Promise((resolve) => {
    exec(command, (error) => {
      if (error) {
        console.error("打开程序失败:", error);
        resolve({ success: false, error: error.message });
      } else {
        resolve({ success: true });
      }
    });
  });
});
function onAppDoubleClick(app2) {
  const exePath = extractExePath(app2.DisplayIcon || app2.UninstallString || "");
  if (!exePath) {
    console.error("无法获取应用可执行文件路径");
    return;
  }
  return exePath;
}
function extractExePath(raw) {
  const match = raw.match(/"?(.*?\.exe)"/i) || raw.match(/(.*?\.exe)/i);
  return match ? match[1] : null;
}
app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
const getInstalledAppsOther = async () => {
  let apps = await getInstalledApps();
  apps = apps.filter((item) => {
    return item.DisplayIcon && (item.DisplayIcon.includes(".exe") || item.DisplayIcon.includes(".lnk")) && !isUninstallExe(item.DisplayIcon) && item.DisplayName !== "桌面纳管 1.0.0";
  });
  const limit = pLimit(1);
  const tasks = apps.map(
    (appItem) => limit(async () => {
      let cleanPath = appItem.DisplayIcon.replace(/^"+|"+$/g, "").replace(/^\\*"?/, "").replace(/"?\\*$/, "").split(",")[0].trim();
      try {
        const icon = await app.getFileIcon(cleanPath, { size: "large" });
        appItem.image = icon ? icon.toDataURL() : null;
      } catch (e) {
        appItem.image = null;
      }
      appItem.appName = appItem.DisplayName;
    })
  );
  await Promise.all(tasks);
  return apps;
};
const getInstalledApps = () => {
  return new Promise((resolve, reject) => {
    const powershellCommand = `
      $OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new()
      $paths = @(
        "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*",
        "HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*",
        "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*"
      )
      $apps = foreach ($path in $paths) {
        Get-ItemProperty $path | Where-Object { $_.DisplayName }
      }
      $apps | ConvertTo-Json -Depth 3
    `;
    execFile(
      "powershell.exe",
      ["-NoProfile", "-Command", powershellCommand],
      { encoding: "utf8", maxBuffer: 1024 * 1024 * 20 },
      (error, stdout, stderr) => {
        if (error) return reject(error);
        if (stderr && stderr.length > 0) return reject(stderr);
        try {
          const apps = JSON.parse(stdout);
          resolve(apps);
        } catch (e) {
          reject(`JSON 解析失败: ${e}`);
        }
      }
    );
  });
};
function isUninstallExe(p) {
  const lower = p.toLowerCase();
  return lower.includes("uninstall") || lower.includes("uninst");
}
app.whenReady().then(createWindow);
export {
  MAIN_DIST,
  RENDERER_DIST,
  VITE_DEV_SERVER_URL
};
